#import "AliTrtcPlugin.h"
#import "ChatRoomViewController.h"

@implementation AliTrtcPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
  FlutterMethodChannel* channel = [FlutterMethodChannel
      methodChannelWithName:@"ali_trtc_plugin"
            binaryMessenger:[registrar messenger]];
  AliTrtcPlugin* instance = [[AliTrtcPlugin alloc] init];
  [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([@"createAudioAndVideoRoomChannel" isEqualToString:call.method]){
      // 创建音视频房间
      NSDictionary *dict = call.arguments;
      NSString *userName = dict[@"userName"];
      NSString *channel = dict[@"channel"];
      [self loginRequestName:userName channelName:channel appid:dict[@"appID"] appkey:dict[@"appKey"] isCreate:NO];
      result(@"创建音视频房间成功");
  } else if ([@"joinAudioAndVideoRoom" isEqualToString:call.method]) {
      // 加入指定的音视频房间
      NSDictionary *dict = call.arguments;
      NSString *userName = dict[@"userName"];
      NSString *channel = dict[@"channel"];
      [self loginRequestName:userName channelName:channel appid:dict[@"appID"] appkey:dict[@"appKey"] isCreate:YES];
      result(@"加入指定的音视频房间成功");
  } else {
    result(FlutterMethodNotImplemented);
  }
}

//登陆请求
- (void)loginRequestName:(NSString *)name channelName:(NSString *)channelName appid:(NSString *)appid appkey:(NSString *)appkey isCreate:(BOOL)isCreate{
    NSLog(@"name = %@ channelName = %@ appid = %@  appKey = %@", name, channelName, appid, appkey);
    ChatRoomViewController *chatRoom = [[ChatRoomViewController alloc] init];
    chatRoom.channelNumber = channelName;
    chatRoom.userName = name;
    chatRoom.appid = appid;
    chatRoom.appkey = appkey;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:chatRoom];
    nav.modalPresentationStyle  = UIModalPresentationFullScreen;
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:nav animated:NO completion:^{
            if (isCreate) {
                UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                pasteboard.string = channelName;
            }
        }];
}

@end
